package com.gougou.common.util;

import com.gougou.common.entity.MyException;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

public class Util {
    /*********************************
     * 检查数据是否为空,为空并抛出自定义错误消息
     * 1.检查string
     * 2.检查int
     * 2.检查obj
     *
     * @param data
     * @param errorMsg
     * @return
     * @throws MyException
     * ***********************************
     */

    public static String checkNull(String data, String errorMsg) throws MyException {
        if (data == null || "".equals(data)) {
            throw new MyException(errorMsg);
        }
        return data;
    }

    public static int checkNull(int data, String errorMsg) throws MyException {
        if (data == 0) {
            throw new MyException(errorMsg);
        }
        return data;
    }

    public static Object checkNull(Object data, String errorMsg) throws MyException {
        if (data == null) {
            throw new MyException(errorMsg);
        }
        return data;
    }

    /******************************************
     *  判断一个集合是否为null，再判断数组有没有值
     *
     * @param list
     * @param errorMsg
     * @return
     * @throws MyException
     * ******************************************
     */
    public static List checkListNull(List list, String errorMsg) throws MyException {
        if (list == null) {
            throw new MyException(errorMsg);
        }
        if (list.size() == 0) {
            throw new MyException(errorMsg);
        }
        return list;
    }


    /*****************************************
     * 将父类所有的属性COPY到子类中。
     * 类定义中child一定要extends father；
     * 而且child和father一定为严格javabean写法，属性为deleteDate，方法为getDeleteDate
     * @param father
     * @param child
     * @return
     * ****************************************
     */
    public Object fatherToChild(Object father, Object child) {
        if (!(child.getClass().getSuperclass() == father.getClass())) {
            System.err.println("child不是father的子类");
        }
        Class fatherClass = father.getClass();
        Field ff[] = fatherClass.getDeclaredFields();

        for (int i = 0; i < ff.length; i++) {
            Field f = ff[i];//取出每一个属性，如deleteDate
            Class type = f.getType();

            try {
                Method m = fatherClass.getMethod("get" + upperHeadChar(f.getName()));//方法getDeleteDate
                Object obj = m.invoke(father);//取出属性值
                f.set(child, obj);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return child;

    }

    /**
     * 首字母大写，in:deleteDate，out:DeleteDate
     */
    private static String upperHeadChar(String in) {
        String head = in.substring(0, 1);
        String out = head.toUpperCase() + in.substring(1, in.length());
        return out;
    }



}
